//
//  RGCommentView.m
//  RedGrass
//
//  Created by wukong on 2018/12/14.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGCommentView.h"
#import "RGCommentToolBarView.h"
#import "RGCommentViewCell.h"
#import "RGCommentContentView.h"
#import <MJRefresh.h>
#import "RGRecommentListModel.h"
#import "UIView+Toast.h"

@interface RGCommentView()<UIGestureRecognizerDelegate,RGCommentToolBarViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UIView *containerView;
@property (strong, nonatomic) UILabel *commentCountLabel;
@property (strong, nonatomic) UIButton *closeBtn;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIView *textViewcontainer;
@property (strong, nonatomic) UILabel *placeHolderLabel;
@property (strong, nonatomic) UIButton *editCommentBtn;
@property (strong, nonatomic) RGCommentToolBarView *barView;
@property (strong, nonatomic) MJRefreshNormalHeader *freshHeader;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *freshFooter;
@property (strong, nonatomic) UILabel *backGroudViewLabel;

@property (strong, nonatomic) NSMutableArray *commentList;
@property (assign, nonatomic) BOOL isAddMainComment;
@property (assign, nonatomic) NSInteger chosedIndex;
@property (strong, nonatomic) NSIndexPath *chosedIndexPath;




@end

@implementation RGCommentView

-(instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        
        [self initUI];
        [self addMasonry];
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGuesture:)];
        tapGestureRecognizer.delegate = self;
        [self addGestureRecognizer:tapGestureRecognizer];
         self.isAddMainComment = YES;
        _barView = [[RGCommentToolBarView alloc]init];
        _barView.delegate = self;
        AA_WEAK_MAKE(self) weakSlef = self;
        [_barView setToolBarTextViewTouchedBlock:^{
            weakSlef.chosedIndex = 0;
            weakSlef.chosedIndexPath = nil;
            weakSlef.isAddMainComment = YES;
        }];
    }
    return self;
}

-(void)initUI{
    self.backgroundColor = [UIColor clearColor];

    self.containerView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, KScreenHeight*3/4);
    [self addSubview:self.containerView];

    UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10.0f, 10.0f)];
    CAShapeLayer* shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];
    self.containerView.layer.mask = shape;
    [self.containerView addSubview:self.commentCountLabel];
    [self.containerView addSubview:self.closeBtn];
    [self.containerView addSubview:self.tableView];
    [self.containerView addSubview:self.backGroudViewLabel];
    [self.containerView addSubview:self.textViewcontainer];
}

-(void) addMasonry{
    [_commentCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.containerView).mas_offset(0);
        make.top.mas_equalTo(self.containerView).mas_offset(12);
        make.height.mas_equalTo(15);
    }];
    
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(self.containerView).mas_offset(10);
        make.right.mas_equalTo(self.containerView).mas_offset(-15);
        make.centerY.mas_equalTo(self.commentCountLabel.mas_centerY).mas_offset(0);
    }];
    
    [_textViewcontainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.containerView).mas_offset(0);
        if(KIsiPhoneX){
            make.bottom.mas_equalTo(self.containerView).mas_offset(0 + 34);
        }else{
            make.bottom.mas_equalTo(self.containerView).mas_offset(0);
        }
        
        make.height.mas_equalTo(50);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.commentCountLabel.mas_bottom).mas_offset(8);
        make.left.and.right.mas_equalTo(self.containerView).mas_offset(0);
//
//        if(KIsiPhoneX){
//            make.bottom.mas_equalTo(self.containerView).mas_offset(50 + 34);
//        }else{
//            make.bottom.mas_equalTo(self.containerView).mas_offset(50);
//        }
        make.bottom.mas_equalTo(self.textViewcontainer.mas_top).mas_offset(0);
    }];
    
    [_backGroudViewLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.commentCountLabel.mas_bottom).mas_offset(8);
        make.left.and.right.mas_equalTo(self.containerView).mas_offset(0);
        make.bottom.mas_equalTo(self.textViewcontainer.mas_top).mas_offset(0);
    }];
  
}

-(void) initTextViewContainer{
   
    [_textViewcontainer addSubview:self.placeHolderLabel];
    [_textViewcontainer addSubview:self.editCommentBtn];
    [_placeHolderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.textViewcontainer).mas_offset(15);
        make.right.mas_equalTo(self.textViewcontainer).mas_offset(-15);
        make.top.mas_equalTo(self.textViewcontainer).mas_offset(8);
        make.bottom.mas_equalTo(self.textViewcontainer).mas_offset(-8);
    }];
    
    [_editCommentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
}

-(NSInteger)getAllCommentCount {
    NSInteger count = _commentList ? _commentList.count : 0;
    if (count > 0) {
        for (RGRecommentListModel *commenModel in _commentList) {
            count += commenModel.childCommentsList ? commenModel.childCommentsList.count : 0;
        }
    }
    return count;
}

#pragma mark - tableView delegate

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _commentList.count;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_commentList.count == 0){
        return 0;
    }
     RGRecommentListModel *commenModel = _commentList[section];
//    return [commenModel.childCommentsList count] ? 1: 0;
    return [commenModel.childCommentsList count];
}

-(CGFloat) tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{
    if(_commentList.count == 0){
        return 0.1f;
    }
    RGRecommentListModel *commenModel = _commentList[section];
    return commenModel.height;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(_commentList.count == 0){
        return 0.1f;
    }
      RGRecommentListModel *commenModel = _commentList[section];
    return commenModel.height;
}

-(CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_commentList.count == 0){
        return 0.1f;
    }
    RGRecommentListModel *commenModel = _commentList[indexPath.section];
    if([commenModel.childCommentsList count]){
        RGChildRecommentListModel *childCommentModel = commenModel.childCommentsList[0];
        return childCommentModel.cellHeight;
    }
    return 0.1f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_commentList.count == 0){
        return 0.1f;
    }
    RGRecommentListModel *commenModel = _commentList[indexPath.section];
    if([commenModel.childCommentsList count]){
        RGChildRecommentListModel *childCommentModel = commenModel.childCommentsList[indexPath.row];
        return childCommentModel.cellHeight;
    }
    return 0.1f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    static NSString *hIdentifier = @"hIdentifier";
    UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:hIdentifier];
   
    if([_commentList count]){
        RGRecommentListModel *commenModel = _commentList[section];
        if(view == nil){
            view = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0,KScreenWidth, commenModel.height)];
            view.backgroundColor = [UIColor yellowColor];
        }
       
        RGCommentContentView *commentHeaderView = [[RGCommentContentView alloc]initWithIsTapEnable:YES];
        commentHeaderView.commenModel = commenModel;
        AA_WEAK_MAKE(self) weakSelf = self;
        [commentHeaderView setActionBtnClickBlock:^(NSInteger tag) {
            if(tag == kListCommentUserTag){//用户

            }else if (tag == kListCommentFavoriteTag){//点赞
                if([weakSelf.commentViewdelegate respondsToSelector:@selector(favoriteCommentWithView:chosedIndex:)]){
                    [weakSelf.commentViewdelegate favoriteCommentWithView:weakSelf chosedIndex:section];
                }

            }else if (tag == kListCommentRepeatTag){//回复
                [weakSelf.barView.textView becomeFirstResponder];
                weakSelf.isAddMainComment = NO;
                weakSelf.chosedIndex = section;
                weakSelf.chosedIndexPath = nil;
            }
        }];
        [view addSubview:commentHeaderView];
        [commentHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view).mas_offset(16);
            make.top.and.bottom.mas_equalTo(view).mas_offset(0);
            make.right.mas_equalTo(view).mas_offset(0);
        }];
    }
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RGCommentViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RGCommentViewCell" forIndexPath:indexPath];
    if(_commentList.count){
        RGRecommentListModel *commenModel = _commentList[indexPath.section];
        if([commenModel.childCommentsList count]){
            RGChildRecommentListModel *childCommentModel = commenModel.childCommentsList[indexPath.row];
            cell.childCommenModel = childCommentModel;
            AA_WEAK_MAKE(self) weakSelf = self;
            [cell setCellBtnClickBlock:^(NSInteger tag) {
                if(tag == kListCommentUserTag){//用户
                    
                }else if (tag == kListCommentFavoriteTag){//点赞
                    if([weakSelf.commentViewdelegate respondsToSelector:@selector(favoriteChildCommentWithView:chosedIndexPath:)]){
                        [weakSelf.commentViewdelegate favoriteChildCommentWithView:weakSelf chosedIndexPath:indexPath];
                    }
                }else if (tag == kListCommentRepeatTag){//回复
                    weakSelf.isAddMainComment = NO;
                    weakSelf.chosedIndexPath = indexPath;
                    weakSelf.chosedIndex = indexPath.section;
                    [weakSelf.barView.textView becomeFirstResponder];
                }
            }];
        }
    }
    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.isAddMainComment = NO;
    self.chosedIndex = indexPath.section;
    self.chosedIndexPath = indexPath;
    [self.barView.textView becomeFirstResponder];
}


#pragma mark - public

//update method
- (void)show {
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    [window addSubview:self];
    [UIView animateWithDuration:0.15f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGRect frame = self.containerView.frame;
                         frame.origin.y = frame.origin.y - frame.size.height;
                         self.containerView.frame = frame;
                     }
                     completion:^(BOOL finished) {
                     }];
    [self.barView show];
}

- (void)dismiss {
    [UIView animateWithDuration:0.15f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGRect frame = self.containerView.frame;
                         frame.origin.y = frame.origin.y + frame.size.height;
                         self.containerView.frame = frame;
                     }
                     completion:^(BOOL finished) {
                         [self removeFromSuperview];
                         [self.barView dismiss];
                     }];
}

#pragma mark - toolbar delegate

-(void) onSendText:(NSString *)text WithView:(RGCommentToolBarView *)view{
    if(_isAddMainComment){
        if([self.commentViewdelegate respondsToSelector:@selector(addMainCommentWithView:content:)]){
            [self.commentViewdelegate addMainCommentWithView:self content:text];
        }
    }else{
        if([self.commentViewdelegate respondsToSelector:@selector(addChildCommentWithView: path: chosedIndex:content:)]){
            [self.commentViewdelegate addChildCommentWithView:self path:_chosedIndexPath chosedIndex:_chosedIndex content:text];
        }
    }
}



-(void) reloadCommentTabelViewWithCommentList:(NSMutableArray *)commentList{
    if(commentList == nil){
        return;
    }
    _commentList = commentList;
    NSInteger count = [self getAllCommentCount];
    _commentCountLabel.text = [NSString stringWithFormat:@"%lu条评论",count];
    if([commentList count]){
        if([self checIsHavebackGroudLabel]){
            [_backGroudViewLabel removeFromSuperview];
        }
    }else{
        if (![self checIsHavebackGroudLabel]) {
            [_containerView addSubview:_backGroudViewLabel];
            [_backGroudViewLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.commentCountLabel.mas_bottom).mas_offset(8);
                make.left.and.right.mas_equalTo(self.containerView).mas_offset(0);
                make.bottom.mas_equalTo(self.textViewcontainer.mas_top).mas_offset(0);
            }];
        }
    }
    [_tableView reloadData];
}

-(BOOL)checIsHavebackGroudLabel{
    BOOL isHave = NO;
    NSArray *views = [_containerView subviews];
    for (UIView *view in views) {
        if([view isKindOfClass:[UILabel class]] && view.tag == 11001){
            isHave = YES;
            break;
        }
    }
    return isHave;
}

-(void) changeFarvoriteStatusWithIndex:(NSInteger)index{
    if(index >= _commentList.count){
        return;
    }
    
//    UITableViewHeaderFooterView *sectionView = [_tableView  headerViewForSection:index];
//    if(sectionView){
//        [self updateSectionViewStyleWithView:sectionView index:index];
//    }
   
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:index];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(void) updateSectionViewStyleWithView:(UITableViewHeaderFooterView *)sectionView index:(NSInteger)index{
    RGCommentContentView *view;
    for (UIView *sub in [sectionView subviews]) {
        if([sub isKindOfClass:[RGCommentContentView class]]){
            view = (RGCommentContentView *)sub;
            break;
        }
    }
    if(view){
         RGRecommentListModel *commenModel = _commentList[index];
        view.commenModel = commenModel;
    }
}

-(void) changeFarvoriteStatusWithIndexPath:(NSIndexPath *)path{
    if(path.section >= _commentList.count){
        return;
    }
    RGRecommentListModel *commenModel = _commentList[path.section];
    if(path.row >= commenModel.childCommentsList.count){
        return;
    }
    
   [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:path,nil] withRowAnimation:UITableViewRowAnimationNone];
}

-(void) resetCommentStauts{
    _isAddMainComment = YES;
    _chosedIndex = 0;
    _chosedIndexPath = nil;
}

-(void) setCommentMjFooterStatusWithNoMoreData{
    _freshFooter.state = MJRefreshStateNoMoreData;
}

-(void) commentMjHeaderLoadingEnd{
    [_freshHeader endRefreshing];
}

-(void) commentMjFooterLoadingEnd{
    [_freshFooter endRefreshing];
}

-(void) showAlertWhenFarvoriteSelfComment{
    [self makeToast:@"不能给自己的评论点赞"];
}

-(void) showAlertWhenCommentSelfComment{
    [self makeToast:@"不能评论自己的评论"];
}

#pragma mark - reponse

-(void)editCommentBtnClick:(UIButton *) button{
    
    _isAddMainComment = YES;
    _chosedIndex = 0;
    _chosedIndexPath = nil;
    [_barView show];
   
}

-(void)closeBtnClick:(UIButton *)button{
    [self dismiss];
}

-(void)loadComment{
    if([self.commentViewdelegate respondsToSelector:@selector(loadMainCommentListWithView:)]){
        [self.commentViewdelegate loadMainCommentListWithView:self];
    }
}

-(void)loadMoreComment{
    if([self.commentViewdelegate respondsToSelector:@selector(loadMoreMainCommentListWithView:)]){
        [self.commentViewdelegate loadMainCommentListWithView:self];
    }
}



#pragma mark - guesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//    if ([NSStringFromClass([touch.view.superview class]) isEqualToString:@"RGCommentViewCell"]) {
//        return NO;
//    }else {
        return YES;
//    }
}

- (void)handleGuesture:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:_containerView];
    if(![_containerView.layer containsPoint:point]) {
        [self dismiss];
        return;
    }
//    point = [sender locationInView:_closeBtn];
//    if([_closeBtn.layer containsPoint:point]) {
//        [self dismiss];
//    }
}

#pragma mark - getter
-(UIView *)containerView{
    if(!_containerView){
        _containerView = [[UIView alloc]init];
        _containerView.backgroundColor = [UIColor whiteColor];
    }
    return _containerView;
}

-(UILabel *)commentCountLabel{
    if(!_commentCountLabel){
        _commentCountLabel = [[UILabel alloc]init];
        _commentCountLabel.textColor = [UIColor blackColor];
        _commentCountLabel.font = FONT(customBoldFontName, 12);
        _commentCountLabel.text = @"0条评论";
    }
    return _commentCountLabel;
}

-(UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setBackgroundImage:IMAGE_NAMED(@"关闭_评论") forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

-(UILabel *)backGroudViewLabel{
    if(!_backGroudViewLabel){
        _backGroudViewLabel = [[UILabel alloc]init];
        _backGroudViewLabel.text = @"还没有评论，赶紧来抢沙发～";
        _backGroudViewLabel.textColor = UICOLOR_WITH_RGBINT(0x999999);
        _backGroudViewLabel.font = FONT(customFontName, 14);
        _backGroudViewLabel.tag = 11001;
        _backGroudViewLabel.backgroundColor = [UIColor whiteColor];
        _backGroudViewLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _backGroudViewLabel;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[RGCommentViewCell class] forCellReuseIdentifier:@"RGCommentViewCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
//        _tableView.mj_header = self.freshHeader;
        _tableView.mj_footer = self.freshFooter;
        
        
    }
    return _tableView;
}

-(MJRefreshNormalHeader *)freshHeader{
    if(!_freshHeader){
        _freshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadComment)];
        _freshHeader.automaticallyChangeAlpha = YES;
    }
    return _freshHeader;
}

-(MJRefreshAutoNormalFooter *)freshFooter{
    if(!_freshFooter){
        _freshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComment)];
        [_freshFooter setTitle:@"暂时没有更多了" forState:MJRefreshStateNoMoreData];
    }
    return _freshFooter;
}

-(UIView *)textViewcontainer{
    if(!_textViewcontainer){
        _textViewcontainer = [[UIView alloc]init];
        _textViewcontainer.backgroundColor = [UIColor whiteColor];
    }
    return _textViewcontainer;
}

-(UILabel *)placeHolderLabel{
    if (!_placeHolderLabel) {
        _placeHolderLabel = [[UILabel alloc]init];
        _placeHolderLabel.text = @"@说点什么";
        _placeHolderLabel.textColor = UICOLOR_WITH_RGBINT(0x666666);
        _placeHolderLabel.font = FONT(customFontName, FFont_14);
    }
    return _placeHolderLabel;
}

-(UIButton *) editCommentBtn{
    if(!_editCommentBtn){
        _editCommentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_editCommentBtn addTarget:self action:@selector(editCommentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editCommentBtn;
}



@end
